package com.jijs.framework.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jijs.framework.dao.BaseDaoI;
import com.jijs.framework.model.EasyUIDataGrid;
import com.jijs.framework.model.PageHelper;
import com.jijs.framework.model.pmodel.AdeAdminLogs;
import com.jijs.framework.model.pmodel.AdeUserLogs;
import com.jijs.framework.model.tmodel.TadeUser;
import com.jijs.framework.model.tmodel.TadeUserLogs;
import com.jijs.framework.util.StringUtil;

/**
 * 
 * 用户日志管理服务类
 * 
 * @author jijs
 * 
 */
@Service
public class UserLogsManagerService {

	@Autowired
	private BaseDaoI<TadeUserLogs> userLogsDao;
	@Autowired
	private BaseDaoI<TadeUser> userDao;

	/**
	 * 获取浏览器类型报表信息
	 * 
	 * @return
	 */
	public List<String> getBrowseType(String searchType, String month) {

		StringBuffer sql = new StringBuffer(
				"SELECT " + searchType + ",count(ID) FROM ade_user_logs WHERE DATE_SUB(CURDATE(),INTERVAL '" + month
						+ "' MONTH) <= date(OPERATE_TIME)GROUP BY " + searchType + "");
		List<Object[]> objs = userLogsDao.findBySql(sql.toString());
		List<String> browserType = new ArrayList<String>();
		for (Object[] obj : objs) {
			String type = obj[0].toString();
			browserType.add(type);
		}
		return browserType;
	}

	/**
	 * 获取浏览器类型报表信息
	 * 
	 * @return
	 */
	public List<Integer> getUserNumByBrowseType(String searchType, String month) {
		StringBuffer sql = new StringBuffer(
				"SELECT " + searchType + ",count(ID) FROM ade_user_logs WHERE DATE_SUB(CURDATE(),INTERVAL '" + month
						+ "' MONTH) <= date(OPERATE_TIME)GROUP BY " + searchType + "");
		List<Object[]> objs = userLogsDao.findBySql(sql.toString());
		List<Integer> userNum = new ArrayList<Integer>();
		for (Object[] obj : objs) {
			Integer num = NumberUtils.toInt(obj[1].toString());
			userNum.add(num);
		}
		return userNum;
	}

	public EasyUIDataGrid getUserLogs(AdeUserLogs userLogs, PageHelper ph) {

		EasyUIDataGrid dg = new EasyUIDataGrid();
		List<AdeUserLogs> userLogsList = new ArrayList<AdeUserLogs>();
		Map<String, Object> params = new HashMap<String, Object>();
		StringBuffer hql = new StringBuffer();
		hql.append(" from TadeUserLogs t ");
		hql.append(whereHql(userLogs, params));
		hql.append(orderHql(ph));
		List<TadeUserLogs> list = userLogsDao.find(hql.toString(), params, ph.getPage(), ph.getRows());
		if (list != null) {
			for (TadeUserLogs t : list) {
				AdeUserLogs u = new AdeUserLogs();
				u.setUserName(t.getTadeUser().getUserName());
				BeanUtils.copyProperties(t, u);
				userLogsList.add(u);
			}
		}
		dg.setRows(userLogsList);
		dg.setTotal(userLogsDao.count("select count(*) from TadeUserLogs t " + whereHql(userLogs, params), params));
		return dg;
	}

	public EasyUIDataGrid getSearchWordsStatistics(PageHelper ph) {

		EasyUIDataGrid dg = new EasyUIDataGrid();
		List<AdeAdminLogs> userLogsList = new ArrayList<AdeAdminLogs>();
		Map<String, Object> params = new HashMap<String, Object>();

		String sql = "SELECT t.VALUE2,COUNT(t.VALUE2) AS num FROM edu_user_logs t WHERE t.LOG_TYPE = :logType GROUP BY t.VALUE2 ORDER BY num DESC";

		List<Object[]> list = userLogsDao.findBySql(sql, params, ph.getPage(), ph.getRows());

		if (list != null) {
			for (Object[] objects : list) {

				AdeAdminLogs u = new AdeAdminLogs();
				u.setValue2(objects[0].toString());
				u.setTimes(Integer.valueOf(objects[1].toString()));
				userLogsList.add(u);
			}
		}
		dg.setRows(userLogsList);
		dg.setTotal(userLogsDao.countBySql("select count(*) from (" + sql + ") t", params).longValue());

		return dg;
	}

	/**
	 * 拼接的where语句
	 * 
	 * @param dingml
	 * @param params
	 * @return
	 */
	private String whereHql(AdeUserLogs userLogs, Map<String, Object> params) {

		StringBuffer hql = new StringBuffer();
		if (userLogs != null) {
			if (StringUtils.isNotBlank(userLogs.getUserId())) {
				hql.append(" and t.tadeUser.id =:userId");
				params.put("userId", userLogs.getUserId());
			}
			if (userLogs.getTimeStart() != null) {
				hql.append(" and t.operateTime >= :timeStart");
				params.put("timeStart", userLogs.getTimeStart());
			}
			if (userLogs.getTimeEnd() != null) {
				hql.append(" and t.operateTime < :timeEnd");
				params.put("timeEnd", userLogs.getTimeEnd());
			}
			if (StringUtils.isNotBlank(userLogs.getLogType())) {
				hql.append(" and t.logType = :logType ");
				params.put("logType", userLogs.getLogType());
			}
		}
		return hql.toString();
	}

	/**
	 * 拼接的order语句
	 * 
	 * @param dingml
	 * @param params
	 * @return
	 */
	private String orderHql(PageHelper ph) {

		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			if("userName".equals(ph.getSort())) {
				orderString = " order by t.tadeUser.userName " + ph.getOrder();
			}else {
				orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
			}
		}
		return orderString;
	}

	/**
	 * 删除历史记录
	 * 
	 * @param id
	 */
	public void deleteUserLog(String id) {
		userLogsDao.delete(userLogsDao.get(TadeUserLogs.class, id));
	}

	public void log(AdeUserLogs simpleUserLog, Integer logType, String content) {
		log(simpleUserLog, logType, content, null, null);
	}

	public void log(AdeUserLogs simpleUserLog, Integer logType, String content, String value1) {
		log(simpleUserLog, logType, content, value1, null);
	}

	public void log(AdeUserLogs simpleUserLog, Integer logType, String content, String value1, String value2) {

		simpleUserLog.setId(StringUtil.generateUUID());
		simpleUserLog.setValue1(value1);
		simpleUserLog.setValue2(value2);
		simpleUserLog.setContent(content);
		simpleUserLog.setOperateTime(new Date());
		simpleUserLog.setLogType(String.valueOf(logType));

		TadeUserLogs tuserLogs = new TadeUserLogs();
		BeanUtils.copyProperties(simpleUserLog, tuserLogs);

		TadeUser tuser = new TadeUser();
		tuser.setId(simpleUserLog.getUserId());
		tuserLogs.setTadeUser(tuser);

		userLogsDao.save(tuserLogs);
	}

	public List<AdeUserLogs> getCorrelativeWords(String keyword) {

		String hql = " from TadeUserLogs t where t.value2 like :keyword and t.logType = :logType group by t.value2 order by t.operateTime desc ";

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("keyword", "%" + keyword + "%");

		List<TadeUserLogs> tlist = userLogsDao.find(hql, params, 0, 10);
		List<AdeUserLogs> list = new ArrayList<AdeUserLogs>();

		for (TadeUserLogs t : tlist) {
			AdeUserLogs u = new AdeUserLogs();
			// 相关检索词不包含正在检索的词
			if (!keyword.equals(t.getValue2())) {
				u.setValue2(t.getValue2());
				list.add(u);
			}
		}

		return list;

	}

	public List<String> getUserAutoWords(List<String> list, String keyword, String userId) {

		// 获得当前用户的相关检索词
		String hql = " from TadeUserLogs t where t.tuser.id = :userId and  t.logType = :logType and t.value2 like :keyword group by t.value2 order by t.operateTime desc ";

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("keyword", "%" + keyword + "%");

		List<TadeUserLogs> tlist = userLogsDao.find(hql, params, 0, 10);

		for (TadeUserLogs t : tlist) {
			list.add(t.getValue2());
		}

		return list;
	}

	public EasyUIDataGrid dataGrid(AdeUserLogs logInfoSys, PageHelper ph, String ids) {

		EasyUIDataGrid dg = new EasyUIDataGrid();

		List<AdeUserLogs> ul = new ArrayList<AdeUserLogs>();

		Map<String, Object> params = new HashMap<String, Object>();

		String hql = " from TadeUserLogs t where 1=1 ";

		List<TadeUserLogs> l = userLogsDao.find(hql + whereHql(logInfoSys, params) + orderHql(ph), params, ph.getPage(),
				ph.getRows());
		if (l != null && l.size() > 0) {
			for (TadeUserLogs t : l) {
				AdeUserLogs d = new AdeUserLogs();
				BeanUtils.copyProperties(t, d);
				d.setUserName(t.getTadeUser().getLoginName());
				ul.add(d);
			}
		}
		dg.setRows(ul);
		dg.setTotal(userLogsDao.count("select count(*) " + hql + whereHql(logInfoSys, params), params));
		return dg;
	}

	/**
	 * 添加至用户日志
	 * 
	 * @param logInfoUser
	 * @param request
	 * @throws Exception
	 */
	public void add(AdeUserLogs userLog) {

		TadeUserLogs t = new TadeUserLogs();
		// 获得当前IP地址
		BeanUtils.copyProperties(userLog, t);
		if (userLog.getId() == null) {
			t.setId(StringUtil.generateUUID());
			t.setOperateTime(new Date());
			t.setTadeUser(userDao.get(TadeUser.class, userLog.getUserId()));
			userLogsDao.save(t);
		}
	}
}
